<template>
    <div id="app">
      <h1>添加销售</h1>
      <el-form ref="form" :model="sale" label-width="80px" :rules="formRules">
        <el-form-item label="商品名称" prop="productid">
          <el-select v-model="sale.productid" placeholder="商品名称">
            <el-option v-for="(p) in products" :key="p.id" :label="p.name" :value="p.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售单价" prop="price">
          <el-input type="number" v-model="sale.price"></el-input>
        </el-form-item>
        <el-form-item label="销售数量" prop="quantity">
          <el-input type="number" v-model="sale.quantity"></el-input>
        </el-form-item>
        <el-form-item label="销售日期" prop="saledate">
          <el-date-picker v-model="sale.saledate"
                          type="datetime"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">添加</el-button>
        </el-form-item>
      </el-form>
    </div>
</template>

<script>
  export default {
    data() {
      return {
        sale: {},
        products:[],
        formRules:{
          productid:[
            { required: true, message: '请输入销售商品', trigger: 'blur' }
          ],
          price:[{required: true, message: '价格必须填写', trigger: 'blur'}],
          quantity:[{required: true, message: '数量必须为数字值'}],
          saledate:[ { required: true, message: '请选择日期', trigger: 'blur' }]
        }
      }
    },
    created(){
      this.axios({
        url:"/products",
        method:"get"
      }).then((resp)=>{
        this.products=resp.data
      });
    },
    methods: {
      onSubmit() {
        this.$refs["form"].validate((valid)=>{
          //valid表示表单校验的结果 true|false
          if(valid){
            this.axios({
              url:"/sales",
              method:"post",
              data:this.sale
            }).then((resp)=>{
              this.$message(resp.data.msg);
              this.$refs.form.resetFields();
            });
          }
          return valid;
        })

      }
    }
  }
</script>


<style scoped>

</style>
